package com.jml.juc;


import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author:jml
 * @date: 2019/6/4 0004 22:50
 * @description：
 */

public class AtomicIntegerFieldUpdaterDemo {

    public static class Candidate {

        int id;
        volatile int score;
    }
    //对Candidate类中的score字段进行安全操作，这个字段一定要是valatile修饰的并且是Integer类型。
    //不直接new，因为这个是抽象类
    public final static AtomicIntegerFieldUpdater<Candidate> scoreUpdater
            = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");
    //检查Updater是否工作正确
    public static AtomicInteger allScore = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        final Candidate stu = new Candidate();
        Thread[] t = new Thread[10000];
        for (int i = 0; i < 10000; i++) {
            t[i] = new Thread() {
                public void run() {
                    if (Math.random() > 0.4) {
                        //对Candidate指定字段进行自增
                        scoreUpdater.incrementAndGet(stu);
                        allScore.incrementAndGet();
                    }
                }
            };
            t[i].start();
        }
        for (int i = 0; i < 10000;
                i++) {
            t[i].join();
        }
        System.out.println("score=" + stu.score);
        System.out.println("id=" + stu.id);
        System.out.println("allScore=" + allScore);
    }
}
